<template>
  <div class="app-container">
    <el-col :span="3">
      <div class="tree-container">
          <el-tree
            :data="treeData"
            :props="treeProps"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            highlight-current
            @node-click="handleNodeClick"
          >
        </el-tree>
      </div>
    </el-col>
    <el-col :span="21">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="项目" prop="projectId">
          <el-select  v-model="queryParams.projectId"
                      placeholder="=======请选择项目======="
                      @change="handleQuery">
            <el-option
              v-for="item in projectList"
              :key="item.projectId"
              :label="item.projectName"
              :value="item.projectId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="材料名称" prop="materiaName">
          <el-input
            v-model="queryParams.materiaName"
            placeholder="请输入材料名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-if="queryParams.level === 2"
            v-hasPermi="['material:material:add']"
          >新增</el-button>
        </el-col>

        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
        <el-table-column label="序号" align="center" prop="materiaId" />
        <el-table-column label="材料类型" align="center" prop="materiatypeName" />
        <el-table-column label="项目" align="center" prop="projectName" />
        <el-table-column label="材料名称" align="center" prop="materiaName" />
        <el-table-column label="材料规格" align="center" prop="materiaStandard" />
        <el-table-column label="材料单位" align="center" prop="materiaUnit" />
        <el-table-column label="采购总计数量" align="center" prop="purchaseQuantity" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['material:material:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['material:material:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-col>

    <!-- 添加或修改材料对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="项目" prop="projectId" >
          <el-select v-model="form.projectId"
                     clearable
                     :disabled="isProjectSelectDisabled"
                     @keyup.enter.native="handleQuery"
                     style="width: 100%">
            <el-option
              v-for="pro in projectList"
              :label="pro.projectName"
              :value="pro.projectId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="材料类型" prop="materiatypeId">
          <treeselect  v-model="form.materiatypeId"
                       :options="treeData"
                       :normalizer="normalizer"
                       placeholder="请选择材料类型"
                       clearable
                       :disable-branch-nodes="true"
                       @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="材料名称" prop="materiaName">
          <el-input v-model="form.materiaName" placeholder="请输入材料名称" />
        </el-form-item>
        <el-form-item label="材料规格" prop="materiaStandard">
          <el-input v-model="form.materiaStandard" placeholder="请输入材料规格" />
        </el-form-item>
        <el-form-item label="材料单位" prop="materiaUnit">
          <el-input v-model="form.materiaUnit" placeholder="请输入材料单位" />
        </el-form-item>
        <el-form-item label="采购总计数量" prop="purchaseQuantity" >
          <el-input v-model="form.purchaseQuantity" placeholder="请输入采购总计数量" disabled/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMaterial, getMaterial, delMaterial, addMaterial, updateMaterial } from "@/api/material/material";
import {listProjectByUserId} from "@/api/project/project";
import {getTreeData} from "@/api/material/materialType";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Material",
  components: {Treeselect},
  data() {
    return {
      isProjectSelectDisabled: true,
      // 树
      treeData:[],
      treeProps: {
        label: 'materiatypeName',
        children: 'children'
      },
      /** 项目列表 */
      projectList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 材料表格数据
      materialList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materiatypeId: null,
        projectId: null,
        materiaName: null,
        materiaStandard: null,
        materiaUnit: null,
        purchaseQuantity: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectId: [
          { required: true, message: "项目不能为空", trigger: "blur" }
        ],
        materiatypeId: [
          { required: true, message: "材料类型不能为空", trigger: "blur" }
        ],
        materiaName: [
          { required: true, message: "材料名称不能为空", trigger: "blur" }
        ],
        materiaStandard: [
          { required: true, message: "材料规格不能为空", trigger: "blur" }
        ],
        materiaUnit: [
          { required: true, message: "材料单位不能为空", trigger: "blur" }
        ],

      }
    };
  },
  created() {
    this.getProjectByUserId();
  },
  methods: {
    normalizer(node){
      if (node.children && !node.children.length) {
        delete node.children
      }
      // 一级材料没有子节点 禁用
      let isDisabled = false;
      if (node){
        isDisabled = node.children==null && node.level===1;
      }
      return {
        id: node.materiatypeId,
        label: node.materiatypeName,
        children: node.children,
        isDisabled: isDisabled,
      }
    },
    handleNodeClick(data){
      if(data.level===0){
        this.queryParams.materiatypeId=null;
      }
      if(data.level===1){
        this.queryParams.materiatypeId=data.materiatypeId;
        this.queryParams.level=data.level;
      }
      if(data.level === 2) {
        this.queryParams.materiatypeId = data.materiatypeId;
        this.queryParams.level = data.level;
      }
      this.getList();
    },
    getTypeTree(){
      getTreeData().then(res=>{
        this.treeData = [res.data];
      })
    },
    /** 查询项目下拉框 */
    getProjectByUserId(){
      listProjectByUserId().then(resp=>{
        this.projectList=resp.data;
        // 设置默认选中的项目ID为1
        this.queryParams.projectId = 1;
        this.getList();
        this.getTypeTree();
      })
    },
    /** 查询材料列表 */
    getList() {
      this.loading = true;
      listMaterial(this.queryParams).then(response => {
        this.materialList = response.rows;
        this.total = response.total;
        this.loading = false;
        // 根据查询结果调整项目下拉框的可用状态
        if (!this.queryParams.projectId) {
          this.isProjectSelectDisabled = false;
        } else {
          this.isProjectSelectDisabled = true;
        }
      });

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        materiaId: null,
        materiatypeId: null,
        projectId: null,
        materiaName: null,
        materiaStandard: null,
        materiaUnit: null,
        purchaseQuantity: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.materiaId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加材料";
      this.form.purchaseQuantity=0;
      this.form.projectId=this.queryParams.projectId;
      this.form.materiatypeId=this.queryParams.materiatypeId;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const materiaId = row.materiaId || this.ids
      getMaterial(materiaId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改材料";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.queryParams.materiatypeId=this.form.materiatypeId;
      this.queryParams.projectId=this.form.projectId;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.materiaId != null) {
            updateMaterial(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMaterial(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const materiaIds = row.materiaId || this.ids;
      this.$modal.confirm('是否确认删除材料编号为"' + materiaIds + '"的数据项？').then(function() {
        return delMaterial(materiaIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('material/material/export', {
        ...this.queryParams
      }, `material_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.tree-container {
  display: flex;
  justify-content: center;
}
.el-tree{
  width: 100%;
}
/* 调整行间距和字体大小 */
.el-tree-node__content {
  padding: 20px 5px;
}

.el-tree-node__label {
  font-size: 18px;
}

.el-tree-node.is-current > .el-tree-node__content .el-tree-node__label {
  color:#00afff!important;
}

</style>
